package top.anonyeast.controller;

import org.springframework.web.bind.annotation.*;
import top.anonyeast.pojo.IPAddress;
import top.anonyeast.pojo.Student;
import top.anonyeast.service.StudentService;
import top.anonyeast.util.IpUtils;
import top.anonyeast.util.TokenUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class StudentController {
    @Resource(name = "studentService")
    StudentService service;
    @Resource(name = "IPAddressController")
    IPAddressController ipController;

    /**
     * 用户登录
     * @param password
     * @return
     */
    @PostMapping("/login")
    public Map<String,Object> login(HttpServletRequest request,String password){
        Map<String,Object> responseMap = new HashMap<>();
        if ("1234567Aa".equals(password)){
            responseMap.put("code",20000);
            responseMap.put("accessToken", TokenUtil.getToken(3101557244L));
        } else {
            //密码错误
            responseMap.put("code",40000);
            System.out.println(LocalDateTime.now() + " 密码错误: " + password);
            IPAddress ipInfo = ipController.insertLoginFailedIpInfo(request, "密码错误");
            responseMap.put("ipInfo",ipInfo);
        }
        return responseMap;
    }

    @PostMapping("/getCount")
    public int getCount(String keywords){
        System.out.println("获取总条数：");
        System.out.println("keywords = " + keywords);
        if (keywords == null || keywords.length() == 0 || "undefined".equals(keywords)){
            return service.getCount();
        }
        return service.getCountWithKeywords(keywords);
    }

    @PostMapping("/getByPageNum")
    public List<Student> getByPageNum(String keywords,int page_num,int page_size){
        System.out.println("查询：");
        System.out.println("keywords = " + keywords);
        System.out.println("page_num = " + page_num);
        System.out.println("page_size = " + page_size);
        if (keywords == null || keywords.length() == 0 || "undefined".equals(keywords)){
            return service.getByPageNum(page_num,page_size);
        }
        return service.getByPageNumWithKeywords(keywords,page_num,page_size);
    }

    @PostMapping("/deleteByStuNumber")
    public boolean deleteByStuNumber(String stuNumber){
        System.out.println("删除：");
        System.out.println("stuNumber = " + stuNumber);
        return service.deleteByStuNumber(stuNumber);
    }

    @PostMapping("/insert")
    public boolean insertStudent(@RequestBody Student student){
        System.out.println("添加：");
        System.out.println(student);
        return service.insertStudent(student);
    }

    @PostMapping("/modify")
    public boolean updateStudent(@RequestBody Student student){
        System.out.println("修改：");
        System.out.println(student);
        return service.updateStudent(student);
    }
}
